<?php

namespace app\admin\controller\yungift;

use addons\yungift\model\GiftOrder;
use app\admin\model\yungift\FundUser;
use \app\admin\model\yungift\Member;
use \app\admin\model\yungift\Activity;
use app\admin\model\yungift\GiftMain;
use app\common\controller\Backend;
use fast\Date;
use think\Db;

/**
 * 数据概览
 */
class Dashboard extends Backend
{
    public $noNeedRight = ['orderStat', 'activityData'];

    /**
     * 查看
     */
    public function index()
    {
        try {
            Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {
        }

        $this->view->assign([
            'totalMember'   => Member::count(),
            'totalActivity' => Activity::count(),
            'totalGift'     => GiftMain::count(),
            'totalOrder'    => GiftOrder::count(),
        ]);

        $activityList = Activity::getOptionList();
        $activityId = key($activityList);
        $this->view->assign(['activityId' => $activityId]);
        $this->assignconfig('activityId', $activityId);

        return $this->view->fetch();
    }


    /**
     * 订单统计
     */
    public function orderStat()
    {
        if (! $date = $this->request->request('date')) {
            $this->error('时间范围不能为空');
        }
        list($startDate, $endDate) = explode(' - ', $date);
        $startTime = strtotime($startDate);
        $endTime = strtotime($endDate);

        // 数据列表
        $dataList = GiftOrder::where('created_at', 'between time', [$startTime, $endTime])
            ->field('DATE_FORMAT(FROM_UNIXTIME(created_at), "%Y-%m-%d") AS date, COUNT(*) AS count')
            ->group('date')
            ->select();

        // 数据分组
        $statList = [];
        for ($time = $startTime; $time <= $endTime;) {
            $statList[date('Y-m-d', $time)] = ['amount' => 0, 'count' => 0];
            $time += 86400;
        }
        foreach ($dataList as $item) {
            $statList[$item['date']] = $item;
        }
        $result = [
            'categoryList'    => array_keys($statList),
            'orderCountList'  => array_column($statList, 'count'),
            'orderAmountList' => array_column($statList, 'amount'),
        ];

        $this->success('', null, $result);
    }

    /**
     * 活动数据
     */
    public function activityData()
    {
        if (! $activityId = $this->request->request('activity_id')) {
            $this->error('活动ID不能为空');
        }
        if (! $activity = Activity::get($activityId)) {
            $this->error('活动不存在');
        }
        if ($activity->group_ids) {
            $memberCount = Member::where('group_id', 'in', explode(',', $activity->group_ids))->count();
        } else {
            $memberCount = Member::count();
        }

        $result = [
            'memberCount'    => $memberCount,
            'giftCount'      => GiftMain::where('find_in_set(:aid, `activity_ids`)', ['aid' => $activityId])->count(),
            'orderCount'     => GiftOrder::where([
                'type'     => GiftOrder::TYPE_ACTIVITY,
                'model_id' => $activityId
            ])->count(),
            'weekOrderCount' => GiftOrder::where([
                'type'     => GiftOrder::TYPE_ACTIVITY,
                'model_id' => $activityId
            ])->whereTime('created_at', 'week')->count(),
            'giveFundAmount' => FundUser::where('activity_id', $activityId)->sum('amount_give'),
            'useFundAmount'  => FundUser::where('activity_id', $activityId)->sum('amount_use'),
            'leftFundAmount' => FundUser::where('activity_id', $activityId)->sum('amount_left'),
            'backFundAmount' => FundUser::where('activity_id', $activityId)->sum('amount_back'),
        ];

        // 订单列表 - 近一周
        $startTime = Date::unixtime('day', -7);
        $endTime = Date::unixtime('day', 0, 'end');
        $dataList = GiftOrder::where(['type' => GiftOrder::TYPE_ACTIVITY, 'model_id' => $activityId])
            ->where('created_at', 'between time', [$startTime, $endTime])
            ->field('DATE_FORMAT(FROM_UNIXTIME(created_at), "%Y-%m-%d") AS date, COUNT(*) AS count, SUM(amount) AS amount')
            ->group('date')
            ->select();
        // 数据分组
        $statList = [];
        for ($time = $startTime; $time <= $endTime;) {
            $statList[date('Y-m-d', $time)] = ['amount' => 0, 'count' => 0];
            $time += 86400;
        }
        foreach ($dataList as $item) {
            $statList[$item['date']] = $item;
        }
        $result = array_merge($result, [
            'orderCategoryList' => array_keys($statList),
            'orderCountList'    => array_column($statList, 'count'),
            'orderAmountList'   => array_column($statList, 'amount'),
        ]);

        // 礼币数据
        $result['fundAmountGroup'] = [
            ['name' => '花费', 'value' => FundUser::where('activity_id', $activityId)->sum('amount_use')],
            ['name' => '剩余', 'value' => FundUser::where('activity_id', $activityId)->sum('amount_left')],
            ['name' => '退回', 'value' => FundUser::where('activity_id', $activityId)->sum('amount_back')],
        ];

        $this->success('', null, $result);
    }
}
